﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Manage_UploadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            UploadType.Value = Request.Params["type"];
        }
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        if (UploadFile.HasFile)
        {
            Save.Enabled = false;

            //保存提交的文件
            DateTime time = DateTime.Now;

            //判断Upload文件夹下面是否包含当前年、月的文件夹
            int year = time.Year;
            int month = time.Month;

            string upload = Server.MapPath(Toolkit.PathOfUpload);
            #region 映射Upload文件夹
            if (!Directory.Exists(upload))
            {
                Directory.CreateDirectory(upload);
            }
            #endregion

            #region 检查目标文件夹
            if (!Directory.Exists(string.Format("{0}/{1}", upload, year)))
            {
                Directory.CreateDirectory(string.Format("{0}/{1}", upload, year));
            }
            if (!Directory.Exists(string.Format("{0}/{1}/{2}", upload, year, month)))
            {
                Directory.CreateDirectory(string.Format("{0}/{1}/{2}", upload, year, month));
            }
            #endregion

            string uuid = Toolkit.NextUUID;
            string dst = UploadFile.FileName;
            string name = dst.Substring(0, dst.LastIndexOf('.'));
            string ext = dst.Substring(dst.LastIndexOf('.') + 1);

            UploadFile.SaveAs(string.Format("{0}/{1}/{2}/{3}.{4}", upload, year, month, uuid, ext));

            #region 记录附件信息
            if (UploadType.Value == "annex")
            {
                Annex a = new Annex();
                a.ID = uuid;
                a.ArticleID = null;
                a.Title = name;
                a.Extension = ext;
                a.Url = string.Format("{0}/{1}/{2}.{3}", year, month, uuid, ext);

                CmsDataContext db = new CmsDataContext();
                db.Annex.InsertOnSubmit(a);
                db.SubmitChanges();
            }
            #endregion

            string rtnValue = string.Format("{0}|{1}|{2}|{3}|{4}", uuid, name, ext, year, month);
            Response.Write("<script>if (window.opener != undefined){window.opener.returnValue = '" + rtnValue + "';}else{window.returnValue = '" + rtnValue + "';}window.close();</script>");
        }
        else
        {
            Response.Write("<script>window.close();</script>");
        }
    }
}